<?php
require_once dirname(__FILE__).'/class.dc.agendaPlugin.php';
class urlAgenda extends dcUrlHandlers{
	public static function agendaPost($args){
		
		if ($args == '' || ereg('^page/([0-9]*)$', $args)) {
			
			self::agendaAll($args);
		}
		
		if (ereg('^([0-9]{4})/([0-9]{2})/([0-9]{2})$', $args) || ereg('^([0-9]{4})/([0-9]{2})/([0-9]{2})/$', $args))
		{
			//echo 'jour';
			self::agendaDay($args);
			
		}
		if (ereg('^([0-9]{4})/([0-9]{2})$', $args) || ereg('^([0-9]{4})/([0-9]{2})/$', $args))
		{
			//echo 'mois';
			self::agendaMonth($args);
		}
		if (ereg('^([0-9]{4})$', $args) || ereg('^([0-9]{4})/$', $args))
		{
			//echo 'annee';
			self::agendaYear($args);
		}
		
		
		$_ctx =& $GLOBALS['_ctx'];
		$core =& $GLOBALS['core'];
		
		$core->blog->withoutPassword(false);
		
		$params = new ArrayObject();
		$params['post_type'] = 'agenda';
		$params['post_url'] = 'Agenda/'.$args;
		$agenda = new dcAgendaPlugin($GLOBALS['core']);
		$_ctx->posts = $agenda->getPosts($params);
		
		$_ctx->comment_preview = new ArrayObject();
		$_ctx->comment_preview['content'] = '';
		$_ctx->comment_preview['rawcontent'] = '';
		$_ctx->comment_preview['name'] = '';
		$_ctx->comment_preview['mail'] = '';
		$_ctx->comment_preview['site'] = '';
		$_ctx->comment_preview['preview'] = false;
		$_ctx->comment_preview['remember'] = false;
		
		$core->blog->withoutPassword(true);
		
		
		if ($_ctx->posts->isEmpty())
		{
			# No entry
			self::p404();
		}
		
		$post_id = $_ctx->posts->post_id;
		$post_password = $_ctx->posts->post_password;
		
		# Password protected entry
		if ($post_password != '')
		{
			# Get passwords cookie
			if (isset($_COOKIE['dc_passwd'])) {
				$pwd_cookie = unserialize($_COOKIE['dc_passwd']);
			} else {
				$pwd_cookie = array();
			}
			
			# Check for match
			if ((!empty($_POST['password']) && $_POST['password'] == $post_password)
			|| (isset($pwd_cookie[$post_id]) && $pwd_cookie[$post_id] == $post_password))
			{
				$pwd_cookie[$post_id] = $post_password;
				setcookie('dc_passwd',serialize($pwd_cookie),0,'/');
			}
			else
			{
				self::serveDocument('password-form.html','text/html',false);
				exit;
			}
		}
		
		$post_comment =
			isset($_POST['c_name']) && isset($_POST['c_mail']) &&
			isset($_POST['c_site']) && isset($_POST['c_content']) &&
			$_ctx->posts->commentsActive();
		
		# Posting a comment
		if ($post_comment)
		{
			# Spam trap
			if (!empty($_POST['f_mail'])) {
				http::head(412,'Precondition Failed');
				header('Content-Type: text/plain');
				echo "So Long, and Thanks For All the Fish";
				exit;
			}
			
			$name = $_POST['c_name'];
			$mail = $_POST['c_mail'];
			$site = $_POST['c_site'];
			$content = $_POST['c_content'];
			$preview = !empty($_POST['preview']);
			
			if ($content != '')
			{
				if ($core->blog->settings->wiki_comments) {
					$core->initWikiComment();
				} else {
					$core->initWikiSimpleComment();
				}
				$content = $core->wikiTransform($content);
				$content = $core->HTMLfilter($content);
			}
			
			$_ctx->comment_preview['content'] = $content;
			$_ctx->comment_preview['rawcontent'] = $_POST['c_content'];
			$_ctx->comment_preview['name'] = $name;
			$_ctx->comment_preview['mail'] = $mail;
			$_ctx->comment_preview['site'] = $site;
			
			if ($preview)
			{
				$_ctx->comment_preview['preview'] = true;
			}
			else
			{
				# Post the comment
				$cur = $core->con->openCursor($core->prefix.'comment');
				$cur->comment_author = $name;
				$cur->comment_site = html::clean($site);
				$cur->comment_email = html::clean($mail);
				$cur->comment_content = $content;
				$cur->post_id = $_ctx->posts->post_id;
				$cur->comment_status = $core->blog->settings->comments_pub ? 1 : -1;
				$cur->comment_ip = http::realIP();
				
				$redir = $_ctx->posts->getURL();
				$redir .= strpos($redir,'?') !== false ? '&' : '?';
				
				try
				{
					if (!text::isEmail($cur->comment_email)) {
						throw new Exception(__('You must provide a valid email address.'));
					}

					# --BEHAVIOR-- publicBeforeCommentCreate
					$core->callBehavior('publicBeforeCommentCreate',$cur);
					if ($cur->post_id) {					
						$comment_id = $core->blog->addComment($cur);
					
						# --BEHAVIOR-- publicAfterCommentCreate
						$core->callBehavior('publicAfterCommentCreate',$cur,$comment_id);
					}
					
					if ($cur->comment_status == 1) {
						$redir_arg = 'pub=1';
					} else {
						$redir_arg = 'pub=0';
					}
					
					header('Location: '.$redir.$redir_arg);
					exit;
				}
				catch (Exception $e)
				{
					$_ctx->form_error = $e->getMessage();
					$_ctx->form_error;
				}
			}
		}
		
		# The entry
		$core->tpl->setPath($core->tpl->getPath(), dirname(__FILE__).'/templates');
		self::serveDocument('event.html');
		exit;
	}
	public static function agendaDay($args)
	{
		//echo "Agenda : Jour<br />";
		$days = explode('/', $args);
		$timestamp = mktime(0, 0,0, $days[1], $days[2], $days[0]);
		$fin =  mktime(23, 59,59, $days[1], $days[2], $days[0]);
		//echo $args." -> ".$timestamp;
		$_ctx =& $GLOBALS['_ctx'];
		$core =& $GLOBALS['core'];
		$core->blog->withoutPassword(false);
		$params = new ArrayObject();
		$params['post_type'] = 'agenda';
		$params['periode'] = array(date('Y-m-d H:i:s', $timestamp), date('Y-m-d H:i:s', $fin));
		$params['order'] = 'G.date_debut ASC';
		$agenda = new dcAgendaPlugin($GLOBALS['core']);
		$_ctx->posts_params = $params;
        $_ctx->posts = $agenda->getPosts($params);
	
		$core->blog->withoutPassword(true);
		
		if ($_ctx->posts->isEmpty())
		{
			# No entry
			self::p404();
		}
		//var_dump($_ctx->posts);
		//exit;
		$core->tpl->setPath($core->tpl->getPath(), dirname(__FILE__).'/templates');
                self::serveDocument('day.html');
		exit;
	}
	public static function agendaMonth($args)
	{
		$days = explode('/', $args);
		
		if (($days[0] % 4) == 0){
			$nbrjour = array(0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
 		}else{
 			$nbrjour = array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		}
		
		
		$timestamp = mktime(0, 0,0, $days[1], 1, $days[0]);
		$fin =  mktime(23, 59,59, $days[1],$nbrjour[$days[1]], $days[0]);
		
		//echo $args." -> ".$timestamp;
		$_ctx =& $GLOBALS['_ctx'];
		$core =& $GLOBALS['core'];
		$core->blog->withoutPassword(false);
		$params = new ArrayObject();
		$params['post_type'] = 'agenda';
		$params['periode'] = array(date('Y-m-d H:i:s', $timestamp), date('Y-m-d H:i:s', $fin));
		$params['order'] = 'G.date_debut ASC';
		$agenda = new dcAgendaPlugin($GLOBALS['core']);
		$_ctx->posts_params = $params;
        $_ctx->posts = $agenda->getPosts($params);
	
		$core->blog->withoutPassword(true);
		
		if ($_ctx->posts->isEmpty())
		{
			# No entry
			self::p404();
		}
		//var_dump($_ctx->posts);
		//exit;
		$core->tpl->setPath($core->tpl->getPath(), dirname(__FILE__).'/templates');
                self::serveDocument('month.html');
		exit;
	}
	public static function agendaYear($args)
	{
	$days = explode('/', $args);
		
		//echo $args." -> ".$timestamp;
		$timestamp = mktime(0, 0,0, 1, 1, $days[0]);
		$fin =  mktime(23, 59,59, 12,31, $days[0]);
		$_ctx =& $GLOBALS['_ctx'];
		$core =& $GLOBALS['core'];
		$core->blog->withoutPassword(false);
		$params = new ArrayObject();
		$params['post_type'] = 'agenda';
		$params['periode'] = array(date('Y-m-d H:i:s', $timestamp), date('Y-m-d H:i:s', $fin));
		$params['order'] = 'G.date_debut ASC';
		$agenda = new dcAgendaPlugin($GLOBALS['core']);
		$_ctx->posts_params = $params;
        $_ctx->posts = $agenda->getPosts($params);
	
		$core->blog->withoutPassword(true);
		
		if ($_ctx->posts->isEmpty())
		{
			# No entry
			self::p404();
		}
		//var_dump($_ctx->posts);
		//exit;
		$core->tpl->setPath($core->tpl->getPath(), dirname(__FILE__).'/templates');
                self::serveDocument('year.html');
		exit;
	}
	public static function agendaAll($args)
	{
		
		$days = explode('/', $args);
		//$timestamp = mktime(0, 0,0, $days[1], $days[2], $days[0]);
		$fin = time();
		//echo $args." -> ".$timestamp;
		$_ctx =& $GLOBALS['_ctx'];
		$core =& $GLOBALS['core'];
		$core->blog->withoutPassword(false);
		$params = new ArrayObject();
		$params['post_type'] = 'agenda';
		
		//$params['date_in'] = date('Y-m-d H:i:s', $fin);
		$params['order'] = 'G.date_debut ASC';
		$agenda = new dcAgendaPlugin($GLOBALS['core']);
		/*
		 * Commenté car il me manque des billes pour gérer la pagination
		if ($_ctx->nb_entry_per_page === null) {
			$_ctx->nb_entry_per_page = $core->blog->settings->nb_post_per_page;
		}
		if (ereg('page/([0-9]*)', $args))
		{
			if(preg_match('`page/(.*)$`', $args, $matchs))
			{
				$params['limit'] = array(($matchs[1]-1)*$_ctx->nb_entry_per_page,$_ctx->nb_entry_per_page );
			}else{
				
				$params['limit'] = array(0,$_ctx->nb_entry_per_page);
			}
			
		}*/
		//print_r($params);	exit;
		$_ctx->posts_params = $params;
        $_ctx->posts = $agenda->getPosts($params);
	
		$core->blog->withoutPassword(true);
		
		if ($_ctx->posts->isEmpty())
		{
			# No entry
			self::p404();
		}
		//var_dump($_ctx->posts);
		//exit;
		$core->tpl->setPath($core->tpl->getPath(), dirname(__FILE__).'/templates');
                self::serveDocument('all.html');
		exit;
	}
	
	/**
	 * Permet d'utiliser les fleches mois précédent et mois suivant dans le calendrier
	 *
	 * @param String $args
	 * @return void
	 */
	public static function agendaAjax($args){
		global $core;
		$days = explode('/', $args);
//		echo $days[0].'/'.$days[1];
		$agenda = new dcAgendaPlugin($core);
		$params['post_type'] = 'agenda';
		$rs = $agenda->getPosts($params);
		
		$table = widgetsAgenda::_constructAgenda($rs, mktime(0,0,0, $days[1], 1, $days[0]));
		echo $table;
		
		
		exit;
	}
	
	/**
	 * Page 404 personnalisée pour l'agenda
	 *
	 */
	protected static function p404(){
		header('Content-Type: text/html; charset=UTF-8');
		http::head(404,'Not Found');
		$core =$GLOBALS['core']; 
		$core->url->type = '404';
		$core->tpl->setPath($core->tpl->getPath(), dirname(__FILE__).'/templates');
		self::serveDocument('agenda404.html');
		exit;
	}
	
	/**
	 * Flux RSS ou ATOM pour l'agenda
	 *
	 * @param String $args
	 */
	public static function feed($args){
		$type = null;
		$comments = false;
		$cat_url = false;
		$post_id = null;
		$params = array();
		$params['post_type'] = 'agenda';
		$subtitle = '';
		
		$mime = 'application/xml';
		
		$_ctx =& $GLOBALS['_ctx'];
		$_ctx->posts->post_type = 'agenda';
		$core =& $GLOBALS['core'];
		//print_r($args); exit;
		if (preg_match('!^([a-z]{2}(-[a-z]{2})?)/(.*)$!',$args,$m)) {
			$params['lang'] = $m[1];
			$args = $m[3];
			//echo 'a'; exit;
			$_ctx->langs = $core->blog->getLangs($params);
		
			if ($_ctx->langs->isEmpty()) {
				self::p404();
			} else {
				$_ctx->cur_lang = $m[1];
			}
		}

		if (preg_match('#^rss2/xslt$#',$args,$m))
		{
			# RSS XSLT stylesheet
			
			self::serveDocument('rss2.xsl','text/xml');
			//echo 'a';
			exit;
		}
		elseif (preg_match('#^(?:category/(.+)/)?(atom|rss2)(/comments)?$#',$args,$m))
		{
			# All posts or comments feed
			$type = $m[2];
			$comments = !empty($m[3]);
			if (!empty($m[1])) {
				$cat_url = $m[1];
				//echo 'd'; exit;
			}
			//echo 'e'; exit;
		}
		else
		{
			self::p404();
		}
		
		
		
		$tpl = $type.'agenda';
		
		$tpl .= '.xml';
		
		if ($type == 'atom') {
			$mime = 'application/atom+xml';
		}
		$agenda = new dcAgendaPlugin($core);
		$_ctx->posts = $agenda->getPosts($params);
		$_ctx->feed_subtitle = $subtitle;
		$core->tpl->setPath($core->tpl->getPath(), dirname(__FILE__).'/templates');
		header('X-Robots-Tag: '.context::robotsPolicy($core->blog->settings->robots_policy,''));
		self::serveDocument($tpl,$mime);
		exit;
	}
	/**
	 * Permet de générer un flux ics (iCalendar)
	 * 
	 * @param String $args
	 */
	public static function ical($args){
		require_once dirname(__FILE__)."/icalcreator/iCalcreator.class.php";
		global $core, $c_ctx;
		$params = array();	
		
		//$params['date_in'] = date('Y-m-d H:i:s', $fin);
		$params['order'] = 'G.date_debut ASC';
		$agenda = new dcAgendaPlugin($core);
		$params['post_type'] = 'agenda';
		$posts = $agenda->getPosts($params);
		$v = new vcalendar(); // create a new calendar instance
		$v->setConfig( 'icaltest', '192.168.1.5' ); // set Your unique id
		$v->setProperty( 'method', 'PUBLISH' ); // required of some calendar software
		// add event to calendar
		// all calendar components are described in rfc2445
		// a complete iCalcreator function list (ex. setProperty) in iCalcreator manual
		//print_r($posts); exit;
		while($posts->fetch()){
			//print_r($post); exit;
			$debut = strtotime($posts->date_debut);
			$fin = strtotime($posts->date_fin);
			$vevent = new vevent(); // create an event calendar component
			$vevent->setProperty( 'dtstart', array( 'year'=>date('Y',$debut), 'month'=>date('m',$debut), 'day'=>date('d',$debut), 'hour'=>date('H',$debut), 'min'=>date('i',$debut),  'sec'=>date('s',$debut) ));
			$vevent->setProperty( 'dtend',  array( 'year'=>date('Y',$fin), 'month'=>date('m',$fin), 'day'=>date('d',$fin), 'hour'=>date('H',$fin), 'min'=>date('i',$fin),  'sec'=>date('s',$fin) ));
			$vevent->setProperty( 'LOCATION', $core->blog->name ); // property name - case independent
			$vevent->setProperty( 'summary', $posts->post_title );
			$vevent->setProperty( 'description', $posts->post_content );
			$v->setComponent ( $vevent ); // add event to calendar
		}
		$v->returnCalendar();
		exit;
	}
}
?>
